<%
  insert_link = refinery.insert_admin_resources_path({
                  :dialog => true,
                  :update_resource => "current_resource_#{field}",
                  :update_text => "current_resource_text_#{field}",
                  :callback => "resource_changed_#{field}",
                  :field => [f.object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, '_').sub(/_$/, ''), field].join('_'),
                  :current_link => "#{resource.url if resource}",
                  :height => 480,
                  :conditions => local_assigns[:conditions]
                })
 %>
<%= f.hidden_field field %>

<div>
  <%= content_tag(:div, id: "no_resource_selected_#{field}", style: ("display: none;" if resource)) do %>
    <%= action_icon :add, insert_link, t('.name'), id: "current_resource_link_#{field}" %>
  <% end %>

  <div id="current_resource_container_<%= field %>" style="margin-top: 10px;<%= ' display: none;' unless resource %>">
    <span class="current_resource" id="<%="current_resource_text_#{field}"%>">
      <%= "#{resource.title} (#{resource.file_name})" if resource %>
    </span>
    <div id='resource_actions'>
      <%= action_icon :download, "#{resource.url if resource}", t('.download_current'), id: "current_resource_#{field}" %>
      <%= action_icon :remove, '#', t('.remove_current'), :id => "remove_resource_#{field}"%>
    </div>
  </div>
</div>

<% content_for :javascripts do %>
  <script>
    resource_changed_<%= field %> = function(callback_args) {
      $('#remove_resource_<%= field %>').show();
      $('#current_resource_container_<%= field %>').show();
      $('#no_resource_selected_<%= field %>').hide();
      $('iframe#dialog_iframe').dialog('close');
      $('iframe#dialog_iframe').remove().parents('.ui-dialog').remove();
      $('#<%= f.object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, '_').sub(/_$/, '') %>_<%= field %>').val(callback_args.id);
      $('#current_resource_link_<%= field %>').attr('href', $('#current_resource_link_<%= field %>').attr('href').replace(/current_link=([^&])*&/, 'current_link=' + callback_args.href + '&'));
      $('#current_resource_<%= field %>').attr('href', callback_args.href);
      $('#current_resource_text_<%= field %>').html(callback_args.html);
    };

    $(document).ready(function(e) {
      $('#remove_resource_<%= field %>').click(function(e) {
        $('#<%= f.object_name %>_<%= field %>').val('');
        $('#current_resource_container_<%= field %>').hide();
        $('#current_resource_text_<%= field %>').html('');
        $('#no_resource_selected_<%= field %>').show();
        $('#current_resource_link_<%= field %>').attr('href', $('#current_resource_link_<%= field %>').attr('href').replace(/current_link=([^&])*&/, 'current_link=&'));
        $(this).hide();
        e.preventDefault();
      });
    });
  </script>
<% end %>
